import fetch from 'dva/fetch';
import Cookie from 'js-cookie';

console.log(process.env.NODE_ENV)

function parseJSON(response) {
  return response.json();
}

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}
//'api/list'   {pagenum:1,limit:5}  [pagenum,limit]
function formatURL(url,params){
    if(url.includes('?')){
        return url
    }

    url = url + '?';

    Object.keys(params).forEach(key => {
        url += `${key}=${params[key]}&`
    })

    return url.slice(0,-1)
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       请求地址
 * @param  {string} method    请求方式
 * @param  {object} params    传递的参数
 * @return {object}           An object containing either "data" or "err"
 */
function request(url,method,params={}) { //{pagenum:1,limit:5}
    
    if(process.env.NODE_ENV === 'development'){
        //如果是开发环境
        url = '/api'+url;
    }

    url = method === 'GET' ? formatURL(url,params) : url;

    const options = {
        method,
        headers:{
            // token
            authorization:Cookie.get('userToken') ? Cookie.get('userToken') : ''
        }
    }

    

    if(method === 'POST' || method === 'PUT' || method === 'DELETE'){
        if(params instanceof FormData){ //如果当前传递的参数伟formdata
            options.headers = {
                ...options.headers
            };
            options.body = params;
        }else{
            options.headers = {
                ...options.headers,
                'content-type':'application/json' 
            };
            options.body = JSON.stringify(params);
        }
    }

    

    return fetch(url, options)
        .then(checkStatus)
        .then(parseJSON)
        .then(data => ({ ...data }))
        .catch(err => ({ err }));
}

export default {
    get(url,params){
        return request(url,'GET',params);
    },
    post(url,params){
        return request(url,'POST',params);
    }
}